const connection = require('../app/databases');

class FileService {
  async selectAvatarDoesItExist(userId) {
    try {
      const statement = `SELECT * FROM avatar WHERE user_id = ?;`;
      const [result] = await connection.execute(statement, [userId]);

      return result;
    } catch (error) {
      return error.message
    }
  }

  async saveAvatarInfo(userId, filename, mimetype, size) {
    try {
      const statement = `INSERT INTO avatar (filename, mimetype, size, user_id) VALUES (?, ?, ?, ?);`;
      const [result] = await connection.execute(statement, [filename, mimetype, size, userId]);

      return result;
    } catch (error) {
      return error.message
    }
  }

  async updateAvatarInfo(userId, filename, mimetype, size) {
    try {
      // 获取修改前头像的名称
      const statement1 = `SELECT filename FROM avatar WHERE user_id = ?`;
      const [result1] = await connection.execute(statement1, [userId]);
      
      // 修改头像信息
      const statement2 = `UPDATE avatar SET filename = ?, mimetype = ?, size = ? WHERE user_id = ?;`;
      const [result2] = await connection.execute(statement2, [filename, mimetype, size, userId]);

      return result1[0];
    } catch (error) {
      return error.message
    }
  }

  async updateAvatar(userId, avatarPath) {
    // console.log(userId, avatarPath);
    try {
      const statement = `UPDATE user SET avatar_url = ? WHERE id = ?`;
      const [result] = await connection.execute(statement, [avatarPath, userId]);

      return result;
    } catch (error) {
      return error.message
    }
  }
}

module.exports = new FileService();